#!/usr/bin/env python
# coding=utf-8
# CopyRight(c) 2019 Inspur Electronic Information Industry Co.,Ltd

"""
    secchecksuite/export.py
    测评工具套件导出函数
    :CopyRight(c) 2019 Inspur Electronic Information Industry Co.,Ltd
"""
import io
import json
import collections
import seccheck_log
import xmltodict
import check
import utils


def export_result(result_file, file_type='json'):
    """
    export results
    Args:
        result_file: plugins exec result file
        file_type: result file type for export
    Raises:
        BaseException:  An error occurred in export result
    """
    seccheck_log.sec_check_logger.info('export {} type file result'.format(file_type))
    try:
        plugins_result_list = []
        with io.open(result_file) as f:
            for line in f:
                plugins_result_list.append(json.loads(line))
    except Exception as e:
        seccheck_log.sec_check_logger.error('file {} unexisted: {}'.format(result_file, e))
    else:
        if file_type.lower() == 'json' or file_type.lower() == 'xml':
            generate_report(plugins_result_list, file_type)
        else:
            seccheck_log.sec_check_logger.error('type is unknown')


def generate_report(plugins_result_list, export_type):
    """
    generate report that is json type
    Args:
        export_type: json /xml
        plugins_result_list: plugins exec result list
    Raises:
        BaseException:  An error occurred in export result
    """
    seccheck_log.sec_check_logger.info('generate {} type report begin'.format(export_type))
    plugins_result_dict = collections.OrderedDict()
    pass_count = 0
    warn_count = 0
    info_count = 0
    scripts__pass_list = []
    scripts__warn_list = []
    scripts__info_list = []
    for plugin_result_dict in plugins_result_list:
        for k in plugin_result_dict:
            script_des = plugin_result_dict[k]
            if k == 'PASS':
                pass_count += 1
                scripts__pass_list.append(script_des)
            elif k == 'WARN':
                warn_count += 1
                scripts__warn_list.append(script_des)
            else:
                info_count += 1
                scripts__info_list.append(script_des)
    plugins_result_dict['pass_count'] = pass_count
    plugins_result_dict['warn_count'] = warn_count
    plugins_result_dict['info_count'] = info_count
    plugins_result_dict['pass'] = scripts__pass_list
    plugins_result_dict['warn'] = scripts__warn_list
    plugins_result_dict['info'] = scripts__info_list

    report_info = None
    if export_type.lower() == 'json':
        report_info = json.dumps(collections.OrderedDict(plugins_result_dict), ensure_ascii=False, indent=4)
    elif export_type.lower() == 'xml':
        xml_dict = {'root': plugins_result_dict}
        report_info = xmltodict.unparse(xml_dict, pretty=True)
    seccheck_log.report_logger.error(report_info)
    seccheck_log.sec_check_logger.error('generate {} type report succeeded'.format(export_type))


def output_plugin_result(plugin_info, result):
    """
    parse plugin result that plugin returns
    Args:
        plugin_info: plugin info list
        result: plugins returns result
    Returns:
        plugin_result_dict: plugin result after parse
    """
    if not check.check_not_none_dict(plugin_info):
        return None
    seccheck_log.sec_check_logger.info('parse result that plugin returns begin')
    plugin_result_dict = {}
    plugin_dict = {}
    if result['code'] == 0:
        flag = 'PASS'
    elif result['code'] == 1:
        flag = 'WARN'
    else:
        flag = 'INFO'
    python = utils.judge_python()
    detail = python.decode(result['des'])
    result_info = '%s %s %s' % (flag, plugin_info.get('plugin_name', None), detail)
    seccheck_log.sec_check_logger.error(result_info)
    plugin_dict['plugin_name'] = plugin_info.get('plugin_name', None)
    plugin_dict['plugin_config'] = plugin_info.get('plugin_config', None)
    plugin_dict['plugin_level'] = plugin_info.get('plugin_level', None)
    plugin_dict['detail'] = ''.join(detail)
    plugin_result_dict[flag] = plugin_dict
    text = json.dumps(plugin_result_dict, ensure_ascii=False)
    seccheck_log.tmp_logger.error(text)
    seccheck_log.sec_check_logger.info('parse result that plugin returns succeeded')
    return plugin_result_dict
